package com.homedo.common.email.service;


import com.homedo.common.email.bean.EmailInfo;
import com.homedo.common.email.bean.EmailServerHostAndPort;
import com.homedo.common.email.bean.EmailServerInfo;
import com.homedo.common.email.util.EmailUtil;
import com.homedo.common.email.util.FetchingEmailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class EmailReceive {


    private static final Logger logger = LoggerFactory.getLogger(EmailReceive.class);

    /**
     * 获取配置的邮箱服务器的信息
     *
     * @return
     */
    public EmailServerInfo getConfigEmailServerInfo(String username, String password) {

        EmailServerInfo emailServerInfo = new EmailServerInfo();

        emailServerInfo.setUserName(username);

        emailServerInfo.setPassword(password);

        emailServerInfo.setValidate(true);

        logger.info("--------邮件服务器配置信息--------");

        return emailServerInfo;


    }


    /**
     * 根据 EmailServerInfo 信息登陆邮件服务器，返回mail回话对象
     *
     * @param emailServerInfo
     * @return
     */
    public Session loginEmailServer(EmailServerInfo emailServerInfo, boolean useReadProtocol) {
        Session sendMailSession = null;
        Authenticator authentication = null;

        try {
            Properties properties = getProperties(emailServerInfo, useReadProtocol);
            // 如果需要身份认证，则创建一个密码验证器
            if (true) {
                authentication = new Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailServerInfo.getUserName(), emailServerInfo.getPassword());
                    }
                };
            }
            // 获取回话对象
            sendMailSession = Session.getInstance(properties, useReadProtocol ? null : authentication);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return sendMailSession;
    }

    /**
     * 转发第 msgnum 份邮件, 并补充正文和附件
     *
     * @param emailServerInfo
     * @param msgnum
     * @param content
     * @param attachmentFiles
     * @param forwardAddress
     * @return
     */
    public boolean forwardEmail(EmailServerInfo emailServerInfo, int msgnum,
                                String content, String[] attachmentFiles, String[] forwardAddress) {
        Properties properties = new Properties();
        properties.put("mail.store.protocol", "pop3");
        properties.put("mail.pop3s.host", "");
        properties.put("mail.pop3s.port", "");
        properties.put("mail.pop3.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.host", "");
        properties.put("mail.smtp.port", EmailServerHostAndPort.SMTP_PORT);

        Session session = Session.getDefaultInstance(properties);
        try {
            // Get a Store object and connect to the current host
            Store store = session.getStore("pop3s");
            store.connect("",
                    emailServerInfo.getUserName(),
                    emailServerInfo.getPassword());// change the user and
            // password accordingly

            // Create a Folder object and open the folder
            Folder folder = store.getFolder("inbox");
            folder.open(Folder.READ_ONLY);
            Message message = folder.getMessage(msgnum);
            // Get all the information from the message
            String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));

            // 转发的邮件信息
            Message forward = new MimeMessage(session);

            // 设置转发的地址
            if (forwardAddress != null && forwardAddress.length > 0) {
                Address[] addresses = new Address[forwardAddress.length];
                for (int i = 0; i < forwardAddress.length; i++) {
                    addresses[i] = new InternetAddress(forwardAddress[i]);
                }
                forward.setRecipients(Message.RecipientType.TO, addresses);
            } else {
                // 如果未设置转发地址，默认转发给原来的人
                String from = InternetAddress.toString(message.getFrom());
                forward.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(from));
            }

            forward.setSubject("Fwd: " + message.getSubject());
            forward.setFrom(new InternetAddress(to));

            // Create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            // Create a multipart message
            Multipart multipart = new MimeMultipart();
            // set content
            messageBodyPart.setContent(message, "message/rfc822");
            // Add part to multi part
            multipart.addBodyPart(messageBodyPart);
            // Associate multi-part with message

            // Multipart is a container that holds multiple body parts.
            BodyPart bodyPart = new MimeBodyPart();
            bodyPart.setContent(content, "text/html; charset=UTF-8");
            multipart.addBodyPart(bodyPart);
            if (attachmentFiles != null && attachmentFiles.length > 0) { // 存在附件
                for (String fileName : attachmentFiles) { // 遍历所有的附件
                    bodyPart = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(fileName); //得到数据源
                    bodyPart.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart  
                    bodyPart.setFileName(fds.getName());  //得到文件名同样至入BodyPart
                    multipart.addBodyPart(bodyPart);
                }
            }
            // 设置邮件消息的主要内容
            forward.setContent(multipart); //Multipart加入到信件

            forward.saveChanges();

            Transport t = session.getTransport("smtp");
            try {
                // connect to the smpt server using transport instance
                t.connect(emailServerInfo.getUserName(), emailServerInfo.getPassword());
                t.sendMessage(forward, forward.getAllRecipients());
            } finally {
                t.close();
            }

            // close the store and folder objects
            folder.close(false);
            store.close();

            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 回复第 msgnum 份邮件
     *
     * @param emailServerInfo
     * @param msgnum
     * @return
     */
    public boolean replyEmail(EmailServerInfo emailServerInfo, int msgnum, String content, String[] attachmentFiles) {

        Properties properties = new Properties();
        properties.put("mail.store.protocol", "pop3");
        properties.put("mail.pop3s.host", "");
        properties.put("mail.pop3s.port", "");
        properties.put("mail.pop3.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "");
        properties.put("mail.smtp.port", EmailServerHostAndPort.SMTP_PORT);
        Session session = Session.getDefaultInstance(properties);

        Store store = null;
        Folder folder = null;
        try {
            // Get a Store object and connect to the current host
            store = session.getStore("pop3s");
            store.connect("",
                    "",
                    emailServerInfo.getPassword());// change the user and
            // password accordingly

            folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);

            Message message = folder.getMessage(msgnum);
            String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));

            Message replyMessage = new MimeMessage(session);
            replyMessage = (MimeMessage) message.reply(false);
            replyMessage.setFrom(new InternetAddress(to));

            // 设置回复的邮件地址
            replyMessage.setReplyTo(message.getReplyTo());

            // Multipart is a container that holds multiple body parts.
            Multipart bodyPartContainer = new MimeMultipart();
            BodyPart bodyPart = new MimeBodyPart();
            // 设置回复的正文
            bodyPart.setContent(content, "text/html; charset=UTF-8");
            bodyPartContainer.addBodyPart(bodyPart);

            if (attachmentFiles != null && attachmentFiles.length > 0) { // 存在附件
                for (String fileName : attachmentFiles) { // 遍历所有的附件
                    bodyPart = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(fileName); //得到数据源
                    bodyPart.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart  
                    bodyPart.setFileName(fds.getName());  //得到文件名同样至入BodyPart
                    bodyPartContainer.addBodyPart(bodyPart);
                }
            }
            // 设置邮件消息的主要内容
            replyMessage.setContent(bodyPartContainer); //Multipart加入到信件

            // Send the message by authenticating the SMTP server
            // Create a Transport instance and call the sendMessage
            Transport t = session.getTransport("smtp");
            try {
                // connect to the smpt server using transport instance
                t.connect("",
                        emailServerInfo.getPassword());
                t.sendMessage(replyMessage, replyMessage.getAllRecipients());
                return true;
            } finally {
                t.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            // close the store and folder objects
            if (folder != null) {
                try {
                    folder.close(false);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
            if (store != null) {
                try {
                    store.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 按照收件箱邮件的顺序删除第 msgnum 号邮件
     *
     * @param emailServerInfo
     * @param msgnum
     * @return
     */
    public boolean deleteEmailByMsgNum(EmailServerInfo emailServerInfo, int msgnum) {
        try {
            // get the session object
            Properties properties = new Properties();
            properties.put("mail.store.protocol", "pop3");
            properties.put("mail.pop3s.host", "");
            properties.put("mail.pop3s.port", "995");
            properties.put("mail.pop3.starttls.enable", "true");
            Session deleteMailSession = Session.getDefaultInstance(properties);

            // create the POP3 store object and connect with the pop server
            Store store = deleteMailSession.getStore("pop3s");

            store.connect("",
                    emailServerInfo.getUserName(), emailServerInfo.getPassword());

            // create the folder object and open it
            Folder emailFolder = store.getFolder("INBOX");
            emailFolder.open(Folder.READ_WRITE);

            // retrieve the messages from the folder in an array and print it
            Message message = emailFolder.getMessage(msgnum);

            // set the DELETE flag to true
            message.setFlag(Flags.Flag.DELETED, true);
            // expunges the folder to remove messages which are marked deleted
            /*
             * 注意此处需要删除本地数据库的邮件和实际邮箱的邮件，需要添加事务！
			 */
            emailFolder.close(true);
            store.close();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送邮件
     *
     * @param sendMailSession
     * @param emailServerInfo
     * @param email
     * @return
     */
    public boolean sendEmail(Session sendMailSession, EmailServerInfo emailServerInfo, EmailInfo email) {
        try {
            // 根据session创建一个邮件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 创建邮件发送者地址
            Address from = new InternetAddress(emailServerInfo.getUserName());
            // 设置邮件消息的发送者
            mailMessage.setFrom(from);
            // 创建邮件的接收者地址，并设置到邮件消息中
            String[] toAddresseStrings = email.getToAddress();
            Address[] toAddresse = new InternetAddress[toAddresseStrings.length];
            for (int i = 0; i < toAddresseStrings.length; i++) {
                toAddresse[i] = new InternetAddress(toAddresseStrings[i]);
            }
            mailMessage.setRecipients(Message.RecipientType.TO, toAddresse);

            if (email.getCarbonCopy() != null && email.getCarbonCopy().length != 0) {
                String[] ccStrings = email.getCarbonCopy();
                Address[] ccAddresse = new InternetAddress[ccStrings.length];
                for (int i = 0; i < ccStrings.length; i++) {
                    ccAddresse[i] = new InternetAddress(ccStrings[i]);
                }
                mailMessage.setRecipients(Message.RecipientType.CC, ccAddresse);
            }
            if (email.getDarkCopy() != null && email.getDarkCopy().length != 0) {
                String[] bccAddresseStrings = email.getDarkCopy();
                Address[] bccAddresse = new InternetAddress[bccAddresseStrings.length];
                for (int i = 0; i < bccAddresseStrings.length; i++) {
                    bccAddresse[i] = new InternetAddress(bccAddresseStrings[i]);
                }
                mailMessage.setRecipients(Message.RecipientType.BCC, bccAddresse);

            }




            // 设置邮件消息的主题
            mailMessage.setSubject(email.getSubject());

            // Multipart is a container that holds multiple body parts.
            Multipart bodyPartContainer = new MimeMultipart();
            BodyPart bodyPart = new MimeBodyPart();
           // mailMessage.setHeader("inquiryId",email.getInquiryID().toString());
            bodyPart.setContent(email.getContent()+"<input type=\"hidden\" id=\"inquiryId\" value=\""+ email.getInquiryID()+"\"> ", "text/html; charset=UTF-8 " );
            bodyPartContainer.addBodyPart(bodyPart);
            if (!email.getAttachmentFiles().isEmpty()) { // 存在附件
                for (Map map : email.getAttachmentFiles()) { // 遍历所有的附件
                    bodyPart = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(map.get("newName").toString()); //得到数据源
                    bodyPart.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart  
                    bodyPart.setFileName(MimeUtility.encodeText(map.get("oldName").toString()));  //得到文件名同样至入BodyPart
                    bodyPartContainer.addBodyPart(bodyPart);
                }
            }
            // 设置邮件消息的主要内容
            mailMessage.setContent(bodyPartContainer); //Multipart加入到信件

            // 设置邮件消息发送的时间
            mailMessage.setSentDate(new Date());
            // 发送邮件
            Transport.send(mailMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 获取最近的一份邮件，并保存附件
     *
     * @param sendMailSession
     * @param emailServerInfo
     * @return
     */
    public EmailInfo getLatestOneEmailFromStore(Session sendMailSession, EmailServerInfo emailServerInfo) {
        EmailInfo emailInfo = null;
        Store store = null;
        try {
            store = sendMailSession.getStore("imap");
            store.connect(emailServerInfo.getUserName(), emailServerInfo.getPassword());

            FetchingEmailUtil fetchingEmailUtil = new FetchingEmailUtil();

            emailInfo = fetchingEmailUtil.fetchingLatestEmailFromStore(store, true);

            // close the store
            return emailInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (store != null) {
                    store.close();
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取收件箱最近的一份邮件
     *
     * @param sendMailSession
     * @param emailServerInfo
     * @return
     */
    public EmailInfo getLatestOneEmailFromSent(Session sendMailSession, EmailServerInfo emailServerInfo) {
        EmailInfo emailInfo = null;
        Store store = null;
        try {
            store = sendMailSession.getStore("imap");
            store.connect(emailServerInfo.getUserName(), emailServerInfo.getPassword());

            FetchingEmailUtil fetchingEmailUtil = new FetchingEmailUtil();

            emailInfo = fetchingEmailUtil.fetchingLatestEmailFromSent(store, true);

            // close the store
            return emailInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (store != null) {
                    store.close();
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取所有邮件
     *
     * @param sendMailSession
     * @param emailServerInfo
     * @return
     */
    public List<EmailInfo> readAllEmailInfos(Session sendMailSession, EmailServerInfo emailServerInfo) {

        List<EmailInfo> allEmailInfos = null;
        Store store = null;
        try {
            store = sendMailSession.getStore("imap");
            store.connect(emailServerInfo.getUserName(), emailServerInfo.getPassword());

            FetchingEmailUtil fetchingEmailUtil = new FetchingEmailUtil();

            allEmailInfos = fetchingEmailUtil.fetchingAllEmailInfos(store, true);

            // close the store
            return allEmailInfos;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (store != null) {
                    store.close();
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 读取LIMIT邮件
     *
     * @param sendMailSession
     * @param emailServerInfo
     * @return
     */
    public List<EmailInfo> readLimitEmailReceive(Session sendMailSession, EmailServerInfo emailServerInfo, int limit) {

        List<EmailInfo> allEmailInfos = null;
        Store store = null;
        try {
            store = sendMailSession.getStore("imap");
            store.connect(emailServerInfo.getUserName(), emailServerInfo.getPassword());

            FetchingEmailUtil fetchingEmailUtil = new FetchingEmailUtil();

            allEmailInfos = fetchingEmailUtil.fetchingLimitEmailInfos(store, true, limit);

            return allEmailInfos;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (store != null) {
                    store.close();
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 读取LIMIT邮件
     *
     * @param sendMailSession
     * @param emailServerInfo
     * @return
     */
    public List<EmailInfo> readLimitEmailSent(Session sendMailSession, EmailServerInfo emailServerInfo, int limit) {

        List<EmailInfo> allEmailInfos = null;
        Store store = null;
        try {
            store = sendMailSession.getStore("imap");
            store.connect(emailServerInfo.getUserName(), emailServerInfo.getPassword());

            FetchingEmailUtil fetchingEmailUtil = new FetchingEmailUtil();

            allEmailInfos = fetchingEmailUtil.fetchingLimitEmailFromSent(store, true, limit);

            return allEmailInfos;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (store != null) {
                    store.close();
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获得邮件会话属性
     * <b>注：此处需要适配 SMTP、POP3、IMAP</>
     */
    private Properties getProperties(EmailServerInfo emailServerInfo, boolean useReadProtocol) {

        Properties props = new Properties();


        if (useReadProtocol) {
            props.put("mail.imap.host", EmailServerHostAndPort.IMAP_SERVER);
            props.put("mail.imap.port", EmailServerHostAndPort.IMAP_PORT);
            props.put("mail.imap.auth", emailServerInfo.isValidate() ? "true" : "false");
            props.put("mail.store.protocol", "imap");
            props.put("mail.imap.starttls.enable", "true");
        } else {
            props.put("mail.smtp.host", EmailServerHostAndPort.SMTP_SERVER);
            props.put("mail.smtp.port", EmailServerHostAndPort.SMTP_PORT);
            props.put("mail.smtp.auth", emailServerInfo.isValidate() ? "true" : "false");
            props.put("mail.smtp.starttls.enable", "true");
        }

        return props;
    }

    public static void main(String[] args) throws MessagingException, IOException {

          EmailServerInfo emailServerInfo = EmailUtil.getConfigEmailServerInfo("taylor_zhao@vadas-ic.com", "Zzq123456");
//        EmailInfo email = new EmailInfo();
//        email.setContent("这个不错啊");
//        email.setFromAddress(emailServerInfo.getUserName());
//        String[] to = {"156642395@qq.com"};
//
//        //
//
//
//        email.setSubject("dddddddddddddd");
//        email.setToAddress(to);
//        email.setInquiryID(1111111l);
//
//        // EmailServerInfo info = EmailUtil.getConfigEmailServerInfo("taylor_zhao@vadas-ic.com", "Zzq123456");
//        email.setContent("wwwwwwww");
//
//        EmailUtil.sendEmail(emailServerInfo, email);
//        EmailInfo emailInfo = EmailUtil.getLatestOneEmailInfo(emailServerInfo);
        //  System.out.println(emailInfo.getInquiryID());
          List<EmailInfo> emailSent = EmailUtil.getLimitEmailSent(emailServerInfo,10);
//        emailSent.forEach(emails->{
//           // System.out.println(emails.getContent());
//          System.out.println(emails.getInquiryID());
//        });

        // 获取所有邮件
        // List<EmailInfo> emailInfos = EmailTemplateUtil.getAllEmailInfos(emailServerInfo);
        // for(EmailInfo email:emailInfos)
        //System.out.println(emailInfo.getAttachmentFiles().get(0).get("cid"));

//        File file = new File("/home/taylor/uploads/daps-api"+"/"+emailInfo.getInquiryID()+"/");
//
//        File files[] = file.listFiles();
//
//
//        for (File f : files) {
//            System.out.println(f);
//        }


        List<String> list = new ArrayList<String>();
        //目前img标签标示有3种表达式
        //<img alt="" src="1.jpg"/>   <img alt="" src="1.jpg"></img>     <img alt="" src="1.jpg">
        //开始匹配content中的<img />标签
        String content = "<p>Dear <strong>vivian xie</strong></p><p>I am looking ex stock offer for the following item.</p><p><strong>XCF01SVOG20C</strong></p><p>Pls check with date code, Lead time, package and quote your best price.</p><p><br></p><p><br></p><p>d到佛山分公司答复vsdfvsd</p><input type=\"hidden\" id=\"inquiryId\" value=\"22\"><input type=\"hidden\" id=\"inquiryId\" value=\"22\"><input type=\"hidden\" id=\"inquiryId\" value=\"11\"><input type=\"hidden\" id=\"inquiryId\" value=\"33\"><input type=\"hidden\" id=\"inquiryId\" value=\"12\">";
        System.out.println(FindValueByName(content));
    }

    public static String FindValueByName(String content) {
        String ccc = "<input type=\"hidden\" id=\"inquiryId\" value=\"(\\d*)\">";
        Pattern p_img = Pattern.compile(ccc);
        Matcher m_img = p_img.matcher(content);
        boolean result_img = m_img.find();
        if (result_img) {
            String matchStr = m_img.group();
            content = content.replace(matchStr, "");
            m_img = p_img.matcher(content);
            if(m_img.find()){
                content= FindValueByName(content);
            }



        } else {
            System.out.println("aaaaaaaa");
        }
        return content;
    }
}
